package com.app.controller.backstage;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.app.aspect.Log;
import com.app.common.Result;
import com.app.event.ComplaintEvent;
import com.app.mapper.CategoryMapper;
import com.app.model.AdminUserModel;
import com.app.model.CategoryModel;
import com.app.model.ComplaintModel;
import com.app.service.AdminUserService;
import com.app.service.ComplaintService;
import com.app.service.UserService;
import com.app.util.TokenUtils;
import com.app.vo.ComplainVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@Controller
@RestController
@RequestMapping("/szwq")
public class AdminComplaintController {
    @Autowired
    private ComplaintService complaintService;
    @Autowired
    private UserService userService;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ApplicationContext applicationContext;
    //我要投诉
    @PostMapping("/addComplaint")
    public Result<Object> addComplaint(@RequestBody ComplaintModel model) {
        String s = complaintService.addComplaint(model);
        ComplaintModel complaintModel = complaintService.getById(model.getId());
        applicationContext.publishEvent(new ComplaintEvent(complaintModel));
        return Result.success(s);
    }

    //投诉列表
    @GetMapping("/selectComplaintList")
    public Result<Object> selectComplaintList(HttpServletRequest request, Integer page, Integer limit, String keyWord, String selectCrtTime, Integer clue, Integer status, Integer examine, Integer warningStatus, String isJiuquan) {
        if (StrUtil.isNotBlank(isJiuquan)) {
            return Result.success(complaintService.getComplaintList(page, limit, keyWord, selectCrtTime, isJiuquan, clue, status, examine, warningStatus));
        }
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        return Result.success(complaintService.selectComplaintList(page, limit, keyWord, selectCrtTime, user, clue, status, examine, warningStatus));
    }

    /**
     * 出口投诉清单
     *
     * @param keyWord       关键词
     * @param selectCrtTime 选择crt时间
     * @param clue          线索
     * @param status        状态
     * @param examine       检查
     * @param warningStatus 警告状态
     * @param response      响应
     * @throws UnsupportedEncodingException 不支持编码异常
     */
    @GetMapping("/exportComplaintList")
    public void exportComplaintList(String keyWord, String selectCrtTime, Integer clue, Integer status, Integer examine, Integer warningStatus, HttpServletResponse response) throws UnsupportedEncodingException {
        String file = URLEncoder.encode("投诉记录导出_" + "序列" + System.currentTimeMillis(), "UTF-8").replaceAll("\\+", "%20");
        String fullPath = System.getProperty("user.dir") + File.separator + "file/export/excel/" + file + ".xlsx";
        List<ComplaintModel> complaintExports = complaintService.selectComplaintExports(keyWord, selectCrtTime, clue, status, examine, warningStatus);
        // 设置响应头信息
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
//        response.setHeader("Content-Disposition", "attachment; filename=" + fullPath);
        response.setHeader("Content-Disposition", "attachment; filename=\"投诉记录导出_" + "序列" + System.currentTimeMillis() + ".xlsx\"");
        // 输出文件内容到响应流中
        try (OutputStream outputStream = response.getOutputStream()) {
            EasyExcel.write(outputStream, ComplaintModel.class).sheet("投诉记录").doWrite(complaintExports);
        } catch (IOException e) {
            // 处理异常
        }

    }

    //进入投诉列表显示黄灯和红灯的列表
    @GetMapping("/selectNoGreenLightList")
    public Result<Object> selectNoGreenLightList(@RequestParam(defaultValue = "0") Integer page,
                                                 @RequestParam(defaultValue = "10") Integer limit, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        ComplainVo complainVo = complaintService.selectNoGreenLightList(page, limit, user);
        return Result.success(complainVo);
    }

    //删除投诉
    @GetMapping("/deleteComplaintList")
    @Log("删除投诉")
    public Result<Object> deleteComplaintList(HttpServletRequest request, Integer id) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        complaintService.deleteComplaintList(id);
        return Result.success("操作成功");
    }

    //办理
    @GetMapping("/adminExamineComplaint")
    @Log("投诉办理")
    public Result<Object> examineComplaint(HttpServletRequest request, Integer id, Integer status, String remark, String handleRemark, String rejectRemark) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        complaintService.examineComplaint(id, status, remark, handleRemark, rejectRemark, user);
        return Result.success("操作成功");
    }

    //审核
    @GetMapping("/adminExamine")
    @Log("审核")
    public Result<Object> examine(HttpServletRequest request, Integer id, Integer examine, String examineRemark) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        complaintService.examine(id, examine, examineRemark);
        return Result.success("操作成功");
    }

    //修改是否为有效线索
    @GetMapping("/updateClue")
    @Log("修改是否为有效线索")
    public Result<Object> updateClue(Integer id, Integer clue, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        String s = complaintService.updateClue(id, clue);
        return Result.success(s);
    }

    //添加电话回访记录
    @GetMapping("/updateRecord")
    @Log("添加电话回访记录")
    public Result<Object> updateRecord(Integer id, String record, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        String s = complaintService.updateRecord(id, record);
        return Result.success(s);
    }

    @GetMapping("/selectHandle")
    public Result<Object> selectHandle(Integer id, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        return Result.success(complaintService.selectHandle(id));
    }

    /**
     * 后台管理投诉情况修改闭环状态
     *
     * @param id
     * @param circleStatus
     * @param request
     * @return
     */
    @PostMapping("/updateComplaintCircleStatus")
    @Log("修改闭环状态")
    public Result<Object> updateComplaintCircle(Integer id, Integer circleStatus, HttpServletRequest request, String url) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        String flag = complaintService.updateComplaintCircleStatus(id, circleStatus, url);
        return Result.success(flag);
    }

    @PostMapping("/complaint/updateReclassifyIndustry")
    public Result<Object> updateReclassifyIndustry(Integer id, Integer industryId, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        String flag = complaintService.updateReclassifyIndustry(id, industryId);
        return Result.success(flag);
    }

    @GetMapping("/getIndustryList")
    public Result<Object> getIndustry(HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        QueryWrapper<CategoryModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid", 10);
        return Result.success(categoryMapper.selectList(queryWrapper));
    }
}
